package HibernateDAO;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import beans.Proveedor;

public class HibernateProveedorDAO {
	private static HibernateProveedorDAO instancia;
	
	private static SessionFactory sf;

	public static HibernateProveedorDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia=new HibernateProveedorDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<Proveedor> obtenerTodosLosProveedores(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Proveedor p");
		List<Proveedor> listaDeProveedores = new ArrayList<Proveedor>(q.list());
		session.close();
		return listaDeProveedores;
	}
	
	public void guardarUnProveedor(Proveedor proveedor){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(proveedor); 
		session.getTransaction().commit();
		session.close();		
	}	
	
	public void borrarUnProveedor(Proveedor proveedor){
		Session session = sf.openSession();
		session.beginTransaction();
		//session.createQuery("DELETE FROM beans.Lista l WHERE l.proveedor.id = :id").setLong("id", proveedor.getIdProveedor()).executeUpdate();
		session.delete(proveedor); 
		session.getTransaction().commit();
		session.close();
		/*
		Session session = sf.openSession();
		SQLQuery q=session.createSQLQuery("delete from Proveedor p WHERE p.idProveedor =" + proveedor.getIdProveedor());
		session.close();
		*/
	}
	
	public Proveedor obtenerProveedor(String razonSocial){
		// Obtenemos proveedor por 'razonSocial'
		Session session = sf.openSession();
		Query q = session.createQuery("FROM Proveedor p WHERE p.razonSocial = :razonSocial").setString("razonSocial", razonSocial);
		Proveedor prov = (Proveedor) q.uniqueResult();
		session.close();
		return prov;
	}
}